package euler.p051_100;

import euler.MainEuler;
import euler.helper.NaturalHelper;

public class Euler094 extends MainEuler {

    /*
        It is easily proved that no equilateral triangle exists
        with integral length sides and integral area.
        However, the almost equilateral triangle 5-5-6 has an area of 12 square units.

        We shall define an almost equilateral triangle to be a
        triangle for which two sides are equal and the third differs by no more than one unit.

        Find the sum of the perimeters of all almost equilateral
        triangles with integral side lengths and area and
        whose perimeters do not exceed one billion (1,000,000,000).
     */
    public String resolve() {

        int limite = 1000000000;                   // int limite = 1000000000;

        int limiteI2 = (limite + 2) / 3;
        long suma = 0;

        for (int i = 6; i <= limiteI2; i++) {
            long longI = i;
            long longI2 = (long)i*i;

            longI = 8 * longI;
            longI2 = 3 * longI2;

            long n1 = longI2 + longI + 4;

            if (NaturalHelper.isSquare(n1) && ((long)Math.sqrt(n1) * longI) % 4 == 0) {
                suma+=(3*i+2);

            } else {
                n1 = longI2 - longI + 4;

                if (NaturalHelper.isSquare(n1) && ((long)Math.sqrt(n1) * longI) % 4 == 0) {
                    suma+=(3*i-2);
                    continue;
                }
            }
        }

        return String.valueOf(suma);
        // 518408346
    }

}
